import { renderToString } from "vue/server-renderer";
import express from "express";
import fs from "fs";
import { createApp } from "./app.js";

const server = express();

server.get("/", async (req, res) => {
  try {
    // 模拟获取的数据
    const storeState = {
      count: Math.floor(Math.random() * 10),
    };
    const app = createApp(storeState);
    // 转换成字符串
    const html = await renderToString(app);
    // 获取html文件
    const template = fs.readFileSync("./index.html", "utf-8");
    const finalHtml = template
      .replace("<!-- vue-ssr-render -->", html)
      .replace(
        "<!-- store-state -->",
        `<script>window.__INITIAL_STATE__ = ${JSON.stringify(
          storeState
        )}</script>`
      );
    res.send(finalHtml);
  } catch (error) {
    console.log("error: ", error);
    res.status(500).send("服务器错误");
  }
});

server.use(express.static("."));

server.listen(3001, () => {
  console.log("Server is running on http://localhost:3001");
});
